using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Text;
using ECommerce.DAL;


namespace Entity
{
    /// <summary>
    /// This object represents the Private Fields of TblNewsletterSubscriber.
    /// </summary>

    [System.ComponentModel.DataObject]
    public class TblNewsletterSubscriber : DatabaseUtility
    {
        #region TblNewsletterSubscriber Private Fields


        Int32 _newsletterSubscriberId;
        String _subscriberName = String.Empty;
        String _email = String.Empty;
        Int32 _newsletterGroupId;

        #endregion
        #region TblNewsletterSubscriber Constractor
        /// <summary>
        /// Creates an empty object of TblNewsletterSubscriber. 
        /// This is mainly used to create a new instance of TblNewsletterSubscriber to add a new TblNewsletterSubscriber.
        /// </summary>
        public TblNewsletterSubscriber() { }


        /// <summary>
        /// Used to retrieve employee information from database, 
        /// which is also used by Update method to save information of an existing TblNewsletterSubscriber.
        /// </summary>
        public TblNewsletterSubscriber
        (
            Int32 newsletterSubscriberId,
            String subscriberName,
            String email,
            Int32 newsletterGroupId
        )
        {
            _newsletterSubscriberId = newsletterSubscriberId;
            _subscriberName = subscriberName;
            _email = email;
            _newsletterGroupId = newsletterGroupId;
        }

        #endregion
        #region TblNewsletterSubscriber Properties

        /***********************************************************************************************
                                    -- PROPERTIES --        
         Contains all the properties representing the data fields of the current entity.
         ***********************************************************************************************/

        /// <summary>
        /// This is the Primary key value of the NewsletterSubscriberId, which can't be assigned from the application,
        /// to ensure the data consistancy, by not letting the user to change the PK_TblNewsletterSubscriber to update the data of an another TblNewsletterSubscriber instance.
        /// For view or updation purpose, every TblNewsletterSubscriber will be retrieved thru the proper 'Get' method.
        /// </summary>

        public Int32 NewsletterSubscriberId
        {
            get { return _newsletterSubscriberId; }
        }


        public String SubscriberName
        {
            get { return _subscriberName; }
            set { _subscriberName = value; }
        }

        public String Email
        {
            get { return _email; }
            set { _email = value; }
        }

        public Int32 NewsletterGroupId
        {
            get { return _newsletterGroupId; }
            set { _newsletterGroupId = value; }
        }


        #endregion
        #region TblNewsletterSubscriber Static Methods
        /************************************************************************************
                                    -- CREATE METHOD (STATIC) --
        *************************************************************************************/
        /************************* Architecure note:**********************************
        Note 1:
        This method is specially useful for the case, where we need to use Object Data Source controls.
        For ObjectDataSource/SqlDataSource controls, the insert/update metnod requires paramters methods, rather property based methods.
        However, there is still a way to pass property based objects as method parameter for data source controls, 
        but in that case we could not use Sql type, as view controls or asp parameter control can only contain few of primitive type.
        The main reason to remain the Sql Type in our object architecture is it is faster and contains better way for null value support.
        
        Note 2: 
        Non-primary key: it should be primitive type, as the asp paramter control (included in data source control) supports only primitive types.
        /*****************************************************************************/
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Insert, true)]
        public static Int32 CreateNewTblNewsletterSubscriber
        (
            String subscriberName,
            String email,
            Int32 newsletterGroupId
        )
        {
            //creating an empty TblNewsletterSubscriber object
            TblNewsletterSubscriber tblNewsletterSubscriber = new TblNewsletterSubscriber();
            tblNewsletterSubscriber.SubscriberName = subscriberName;
            tblNewsletterSubscriber.Email = email;
            tblNewsletterSubscriber.NewsletterGroupId = newsletterGroupId;

            return TblNewsletterSubscriber.CreateNewTblNewsletterSubscriber(tblNewsletterSubscriber);
        }

        /************************************************************************************
                 -- UPDATE METHODS (STATIC) --
        *************************************************************************************/

        /************************* Architecure note:**********************************
        Note 1:
        This method is specially useful for the case, where we need to use Object Data Source controls.
        For ObjectDataSource/SqlDataSource controls, the insert/update metnod requires paramters methods, rather property based methods.
        However, there is still a way to pass property based objects as method parameter for data source controls, 
        but in that case we could not use Sql type, as view controls or asp parameter control can only contain few of primitive type.
        The main reason to remain the Sql Type in our object architecture is it is faster and contains better way for null value support.
        
        Note 2: 
        There the two types of paramaters will be passed here.
         * a. Primary key paramater: it should be Sql type, as we will bind the primary key property for the view controls (form view, details view etc) as datakey.
         * b. Non-primary key: it should be primitive type, as the asp paramter control (included in data source control) supports only primitive types.
        /*****************************************************************************/

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static bool UpdateTblNewsletterSubscriber
        (
            Int32 newsletterSubscriberId,
            String subscriberName,
            String email,
            Int32 newsletterGroupId
        )
        {
            TblNewsletterSubscriber tblNewsletterSubscriber = TblNewsletterSubscriber.GetTblNewsletterSubscriberByNewsletterSubscriberId(newsletterSubscriberId);

            tblNewsletterSubscriber.SubscriberName = subscriberName;
            tblNewsletterSubscriber.Email = email;
            tblNewsletterSubscriber.NewsletterGroupId = newsletterGroupId;

            return TblNewsletterSubscriber.UpdateTblNewsletterSubscriber(tblNewsletterSubscriber);
        }

        /************************************************************************************
                         -- DELETE METHODS --
        *************************************************************************************/
        /************************* Architecure note:**********************************
        We have used the employeeId parameter as SqlInt32, to bind the delete method with object data source and view control directly.
        ****************************************************************************/
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static bool DeleteTblNewsletterSubscriber
        (
            Int32 newsletterSubscriberId
        )
        {
            //Validate Input
            if (newsletterSubscriberId <= GetNewsletterSubscriberIdMinValue)
                throw (new ArgumentOutOfRangeException("newsletterSubscriberId"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddParameterToSqlCmd(sqlCmd, "@NewsletterSubscriberId", SqlDbType.Int, 0, ParameterDirection.Input, newsletterSubscriberId);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERSUBSCRIBER_DELETETBLNEWSLETTERSUBSCRIBER);
            ExecuteScalarCmd(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == 0 ? false : true);

        }

        /// <summary>
        /// Deletes a set of employees from the database.
        /// </summary>
        public static bool DeleteTblNewsletterSubscriberList(System.Collections.Generic.List<Int32> newsletterSubscriberIdListToDelete)
        {
            //Validate Input
            foreach (Int32 newsletterSubscriberId in newsletterSubscriberIdListToDelete)
                if (newsletterSubscriberId <= GetNewsletterSubscriberIdMinValue)
                    throw (new ArgumentOutOfRangeException("newsletterSubscriberId"));

            //performing deletion operation //

            string xmlString = FormatXMLForIdArray(newsletterSubscriberIdListToDelete);

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddParameterToSqlCmd(sqlCmd, "@NewsletterSubscriberIdList", SqlDbType.Xml, xmlString.ToString().Length, ParameterDirection.Input, xmlString.ToString());
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERSUBSCRIBER_DELETETBLNEWSLETTERSUBSCRIBERLIST);
            ExecuteScalarCmd(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == newsletterSubscriberIdListToDelete.Count ? true : false);
        }

        /************************************************************************************
                                 -- GET BY PRIMARY METHODS --
        *************************************************************************************/
        /************************* Architecure note:**********************************
        Retrives an Employee from database, based on it's primary key.
        To view or update an employee, everytime we must have to use this type of 'get' method, 
        since we don't have direct access to the Primary key value for assigning value.
        We have used the employeeId parameter as SqlInt32, to bind the delete method with object data source and view control directly.
        /*****************************************************************************/
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static TblNewsletterSubscriber GetTblNewsletterSubscriberByNewsletterSubscriberId(Int32 newsletterSubscriberId)
        {
            if (newsletterSubscriberId <= GetNewsletterSubscriberIdMinValue)
                throw (new ArgumentOutOfRangeException("newsletterSubscriberId"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@NewsletterSubscriberId", SqlDbType.Int, 0, ParameterDirection.Input, newsletterSubscriberId);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERSUBSCRIBER_GETTBLNEWSLETTERSUBSCRIBERBYNEWSLETTERSUBSCRIBERID);
            GenerateCollectionFromReader test = new GenerateCollectionFromReader(GenerateTblNewsletterSubscriberCollectionFromReader);
            CustomCollection<TblNewsletterSubscriber> objCollection = ((CustomCollection<TblNewsletterSubscriber>)ExecuteReaderCmd(sqlCmd, test));

            if (objCollection.Count > 0)
                return objCollection[0];
            else
                return null;
        }

        /************************************************************************************
                         -- GET BY FOREIGN KEY METHODS --
        *************************************************************************************/

        /************************************************************************************
                 -- GET ALL METHODS --
        *************************************************************************************/
        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static CustomCollection<TblNewsletterSubscriber> GetAllTblNewsletterSubscriber()
        {

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERSUBSCRIBER_GETALLTBLNEWSLETTERSUBSCRIBER);
            GenerateCollectionFromReader test = new GenerateCollectionFromReader(GenerateTblNewsletterSubscriberCollectionFromReader);
            CustomCollection<TblNewsletterSubscriber> objCollection = ((CustomCollection<TblNewsletterSubscriber>)ExecuteReaderCmd(sqlCmd, test));

            return objCollection;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static CustomCollection<TblNewsletterSubscriber> GetAllTblNewsletterSubscriberPaged(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            //Validate Input
            if (orderBy == "")
                orderBy = "NewsletterSubscriberId";

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@orderby", SqlDbType.VarChar, 50, ParameterDirection.Input, orderBy);
            AddParameterToSqlCmd(sqlCmd, "@startrow", SqlDbType.Int, 0, ParameterDirection.Input, startRowIndex);
            AddParameterToSqlCmd(sqlCmd, "@pagesize", SqlDbType.Int, 0, ParameterDirection.Input, maximumRows);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERSUBSCRIBER_GETALLTBLNEWSLETTERSUBSCRIBERPAGED);

            GenerateCollectionFromReader test = new GenerateCollectionFromReader(GenerateTblNewsletterSubscriberCollectionFromReader);
            CustomCollection<TblNewsletterSubscriber> objCollection = ((CustomCollection<TblNewsletterSubscriber>)ExecuteReaderCmd(sqlCmd, test));
            return objCollection;
        }

        [System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static int GetAllTblNewsletterSubscriberPagedCount(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();

            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERSUBSCRIBER_GETALLTBLNEWSLETTERSUBSCRIBERPAGEDCOUNT);
            ExecuteScalarCmd(sqlCmd);

            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return returnValue;
        }

        #endregion
        #region Employee Instance Methods
        /************************************************************************************
                                    -- SAVE (INSERT/UPDATE) METHODS (INSTANCE) --
        *************************************************************************************/
        /// <summary>
        /// Saves (inserts and updates) an Employee into database.
        /// The insertion occur if the EmployeeId conatins default value.
        /// Otherwises it updates the Employee into the database, based on the primary key value stored in EmployeeId.
        /// This technique ensures an Employee will not be updated without having a valid EmployeeId.
        /// </summary>
        public bool Save()
        {
            if (NewsletterSubscriberId <= GetNewsletterSubscriberIdMinValue)
            {
                Int32 TempId = CreateNewTblNewsletterSubscriber(this);
                if (TempId > 0)
                {
                    _newsletterSubscriberId = TempId;
                    return true;
                }
                else
                {
                    // error occurs
                    return false;
                }
            }
            else
            {	//This is a update Command
                return (UpdateTblNewsletterSubscriber(this));
            }

        }

        public static Int32 CreateNewTblNewsletterSubscriber(TblNewsletterSubscriber newTblNewsletterSubscriber)
        {
            // validate Parameters
            if (newTblNewsletterSubscriber == null)
                throw (new ArgumentNullException("newTblNewsletterSubscriber"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            int length = 0;
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);

            AddParameterToSqlCmd(sqlCmd, "@SubscriberName", SqlDbType.VarChar, 100, ParameterDirection.Input, newTblNewsletterSubscriber.SubscriberName);
            AddParameterToSqlCmd(sqlCmd, "@Email", SqlDbType.VarChar, 50, ParameterDirection.Input, newTblNewsletterSubscriber.Email);
            AddParameterToSqlCmd(sqlCmd, "@NewsletterGroupId", SqlDbType.Int, 0, ParameterDirection.Input, newTblNewsletterSubscriber.NewsletterGroupId);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERSUBSCRIBER_CREATENEWTBLNEWSLETTERSUBSCRIBER);
            ExecuteScalarCmd(sqlCmd);
            return (Int32.Parse(sqlCmd.Parameters["@ReturnValue"].Value.ToString()));

        }
        /// <summary>
        /// Updates an TblNewsletterSubscriber instance to the database.
        /// </summary>
        public static bool UpdateTblNewsletterSubscriber(TblNewsletterSubscriber newTblNewsletterSubscriber)
        {
            // validate Parameters
            if (newTblNewsletterSubscriber == null)
                throw (new ArgumentNullException("newTblNewsletterSubscriber"));

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            int length = 0;
            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);

            AddParameterToSqlCmd(sqlCmd, "@NewsletterSubscriberId", SqlDbType.Int, 0, ParameterDirection.Input, newTblNewsletterSubscriber.NewsletterSubscriberId);
            AddParameterToSqlCmd(sqlCmd, "@SubscriberName", SqlDbType.VarChar, 100, ParameterDirection.Input, newTblNewsletterSubscriber.SubscriberName);
            AddParameterToSqlCmd(sqlCmd, "@Email", SqlDbType.VarChar, 50, ParameterDirection.Input, newTblNewsletterSubscriber.Email);
            AddParameterToSqlCmd(sqlCmd, "@NewsletterGroupId", SqlDbType.Int, 0, ParameterDirection.Input, newTblNewsletterSubscriber.NewsletterGroupId);

            SetCommandType(sqlCmd, CommandType.StoredProcedure, SPR_TBLNEWSLETTERSUBSCRIBER_UPDATETBLNEWSLETTERSUBSCRIBER);
            ExecuteScalarCmd(sqlCmd);
            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return (returnValue == 0 ? false : true);
        }
        #endregion

        #region TblNewsletterSubscriber Related Collections
        /// <summary>
        /// Creates and returns a strongly typed collection of Employee custom entity. 
        /// The colelction is created through iterating on the IdataReader object which contains Employee information, as a set of records, similar to tabular format.
        /// </summary>
        public static CollectionBase GenerateTblNewsletterSubscriberCollectionFromReader(IDataReader returnData)
        {

            //creating the instance of Employee collection
            CustomCollection<TblNewsletterSubscriber> colTblNewsletterSubscriber = new CustomCollection<TblNewsletterSubscriber>();

            /************************* Architecure note:**********************************
             * Below code includes the null value functionality to retieve the data which has nill value in database end.
             * Design consideration:
             * Besides general data fields, special care should be taken for primary keys, to assign '0'/defaultvalue, rather passing 'Null' value in constructor parameter.
             * Although we are considering sqldb tyoe data for the current data container, but while retireving data from database end, through datareader object, we need to cast data reader objects using .net primitive data type, 
             * rather using sqldb type to cast, since data reader objects don't support sql db type to be casted.
             *****************************************************************************/

            //Iterating thriugh the data reader, to generate Employee collection.

            //getting the Employee collection by iterating thru the data reader
            while (returnData.Read())
            {
                //passing the TblNewsletterSubscriber constructor parameters from the current instance of data reader fields.
                TblNewsletterSubscriber newTblNewsletterSubscriber = new TblNewsletterSubscriber
                (
                    returnData["NewsletterSubscriberId"] == System.DBNull.Value ? GetNewsletterSubscriberIdMinValue : (Int32)returnData["NewsletterSubscriberId"],
                    returnData["SubscriberName"] == System.DBNull.Value ? string.Empty : (String)returnData["SubscriberName"],
                    returnData["Email"] == System.DBNull.Value ? string.Empty : (String)returnData["Email"],
                    returnData["NewsletterGroupId"] == System.DBNull.Value ? 0 : (Int32)returnData["NewsletterGroupId"]

                );
                //adding the Employee to the collection
                colTblNewsletterSubscriber.Add(newTblNewsletterSubscriber);
            }

            //returns the collection of Companys 
            return (colTblNewsletterSubscriber);
        }

        #endregion
        #region Constants and Default Values

        public static Int32 GetNewsletterSubscriberIdMinValue
        {
            get
            {
                return 0;
            }
        }

        //create method related contants
        internal const string SPR_TBLNEWSLETTERSUBSCRIBER_CREATENEWTBLNEWSLETTERSUBSCRIBER = "spr_TblNewsletterSubscriber_CreateNewTblNewsletterSubscriber";
        internal const string SPR_TBLNEWSLETTERSUBSCRIBER_UPDATETBLNEWSLETTERSUBSCRIBER = "spr_TblNewsletterSubscriber_UpdateTblNewsletterSubscriber";
        internal const string SPR_TBLNEWSLETTERSUBSCRIBER_DELETETBLNEWSLETTERSUBSCRIBER = "spr_TblNewsletterSubscriber_DeleteTblNewsletterSubscriber";
        internal const string SPR_TBLNEWSLETTERSUBSCRIBER_DELETETBLNEWSLETTERSUBSCRIBERLIST = "spr_TblNewsletterSubscriber_DeleteTblNewsletterSubscriberList";
        internal const string SPR_TBLNEWSLETTERSUBSCRIBER_GETTBLNEWSLETTERSUBSCRIBERBYNEWSLETTERSUBSCRIBERID = "spr_TblNewsletterSubscriber_GetTblNewsletterSubscriberByNewsletterSubscriberId";
        internal const string SPR_TBLNEWSLETTERSUBSCRIBER_GETALLTBLNEWSLETTERSUBSCRIBER = "spr_TblNewsletterSubscriber_GetAllTblNewsletterSubscriber";
        internal const string SPR_TBLNEWSLETTERSUBSCRIBER_GETALLTBLNEWSLETTERSUBSCRIBERPAGED = "spr_TblNewsletterSubscriber_GetAllTblNewsletterSubscriberPaged";
        internal const string SPR_TBLNEWSLETTERSUBSCRIBER_GETALLTBLNEWSLETTERSUBSCRIBERPAGEDCOUNT = "spr_TblNewsletterSubscriber_GetAllTblNewsletterSubscriberPagedCount";

        #endregion
    }
}
